$(function(){
	//checkProgressName();
//	initPlanPro();
	$("#accPro").change(function() {
		checkStatus();
	});
	$("#currentPro").change(function() {
		getProcessName();
	});
	$("#accPro").change(function() {
		checkAccPro();
	});
});

function initPlanPro(){
	var planStartTime = $("#planStartTime").val();
	var accStartTime = $("#accStartTime").val();
	if(!checkEndTimeTwo(planStartTime,accStartTime)){
		$("#planPro").val(100);
	}
}

function checkProgressName(){
	var planProgressName = $("#planProgress").val();
	var currentPro = $("#processName").val();
	if(currentPro!=planProgressName){
		getProcessName();
	}
}
function checkAccPro(){
	var accPro = $("#accPro").val();
    if (isNaN(accPro))
    {
    	msgFeedBack('请填写数字',"#accPro");
    	$("#accPro").val("");
        return;
    }
    var i=parseInt(accPro);
    if(accPro<=0 || accPro>100)
    {
    	msgFeedBack('完成比例在0-100之间',"#accPro");
    	$("#accPro").val("");
        return;
    }
}

function checkStatus(){
	var planPro = $("#planPro").val();
	var accPro = $("#accPro").val();
	var currentPro = $("#currentPro").val();
	var planProgressName = $("#planProgress").val();
	var planStartTime = $("#planStartTime").val();
	var accStartTime = $("#accStartTime").val();
	var planTotalTime = $("#planTotalTime").val();//计划总天数
	var accTotalTime = $("#accTotalTime").val();//实际计划总天数
	var days = $("#day").val();
    var differTime = $("#differTime").val();//相差天数
    var datas = 0;
	if(currentPro==planProgressName){
		if(Number(accPro)=="100"){
			var nowDay = $("#nowDay").val();//当前是计划开始的第几天
			var advanceDay = Number(planTotalTime)-Number(nowDay);//计算提前天数
			if(advanceDay==0){
				$("#proStatus").val("正常");
			}else if(advanceDay>0){
				$("#proStatus").val("提前");
			}else if(advanceDay<0){
				$("#proStatus").val("延期");
			}
			$("#extDay").val(advanceDay);
            if (Number(differTime) > 0) {//计划结束已经过了 进入这里 进度为100 则为0
                datas = 0;
            }else{
                datas = advanceDay;
            }
		}else if(Number(planPro) > Number(accPro)){
			var day = Math.round((Number(planPro)-Number(accPro))/(100/planTotalTime));
//			alert(d);
//			var day = Math.round(planPro/accPro)-1;/
			if(day>0){
				$("#proStatus").val("延期");
			}else{
				$("#proStatus").val("正常");
			}
			$("#extDay").val(day);
            datas = day;
		}else if(Number(planPro) < Number(accPro)){
			var day = Math.round((Number(accPro)-Number(planPro))/(100/planTotalTime));
			if(day>0){
				$("#proStatus").val("提前");
			}else{
				$("#proStatus").val("正常");
			}
			$("#extDay").val(day);
            datas = day;
		}else if(Number(planPro) == Number(accPro)){
			$("#proStatus").val("正常");
			$("#extDay").val(0);
		}
	}else{
		if(checkEndTime(planStartTime,accStartTime)){
			$("#proStatus").val("提前");
			var advanceDay = Math.floor(planTotalTime*(1-Number(planPro)/100)+accTotalTime*Number(accPro)/100);//计算提前天数
			$("#extDay").val(Number(advanceDay)+Number(days));
            datas = Number(advanceDay)+Number(days);
		}else{
			$("#proStatus").val("延期");
			var delayDay = Math.floor(planTotalTime*Number(planPro)/100+accTotalTime*(1-Number(accPro)/100));//计算延期天数
			$("#extDay").val(Number(delayDay)+Number(days));
            datas = Number(delayDay) + Number(days);
		}
	}
    if (Number(differTime) > 0) {//计划结束已经过了 进入这里
        if (datas < 0) {//不可为负数
            datas = 0;
        }
        $("#extDay").val(datas + Number(differTime));
        $("#proStatus").val("延期");
    }
}

function checkEndTime(startTime,endTime){  
    var start=new Date(startTime.replace("-", "/").replace("-", "/"));  
    var end=new Date(endTime.replace("-", "/").replace("-", "/"));  
    if(end>start){  
        return true;  
    }  
    return false;  
}  

function checkEndTimeTwo(startTime,endTime){  
    var start=new Date(getFormatYMD(startTime).replace("-", "/").replace("-", "/"));  
    var end=new Date(endTime.replace("-", "/").replace("-", "/"));  
    if(end>=start){  
        return true;  
    }  
    return false;  
}

function getProcessName(){
	var currentPro = $("#currentPro").val();
	var modelPlanId = $("#modelPlanId").val();
	var planProgressName = $("#planProgress").val();
	var url = basePath + "/bus/progress/checkProcessStatus";
	var data = {
			currentPro : currentPro,
			modelPlanId : modelPlanId,
			planProgressName : planProgressName
	}
		$.ajax({
			type : "post",
			url : url,
			data : data,
			dataType : "json",
			success : function(data) {
				//if(data.data == '0'){
				//	msgAlert(data.message);
				//	$("#currentPro").val($("#processName").val());
				//}else{
				$("#accPro").val("");
				$("#extDay").val("");
				$("#proStatus").val("");
				$("#accStartTime").val(getFormatYMD(data.data.planStartTime));
				$("#day").val(data.data.day);
					getCompletePro(data.data.accStartTime,data.data.planTotalTime,data.data.planStartTime);
				//}
			}
		});
}
/**
 * 计算完成比例
 */
function getCompletePro(accStartTimeTwo,planTotalTime,planStartTime){
	$("#accTotalTime").val(planTotalTime);
	var day;
	var proportion
	var planStartTime = $("#planStartTime").val();
	var accStartTime = $("#accStartTime").val();
	if(checkEndTime(planStartTime,accStartTime)){
		if(accStartTimeTwo != "" && accStartTimeTwo != null && accStartTimeTwo != "undefined"){
			
		}else{
			day = 1;
			proportion = Math.floor(100/planTotalTime*1);//计算完成比例
		}
	}else{
		if(planStartTime != "" && planStartTime != null && planStartTime != "undefined"){
			 day = DateDiff(getFormatYMD(timeStamp),getFormatYMD(planStartTime));//计算当前时间是计划进行的第几天
	//		 if(timeStamp>accStartTime){
	//			 
	//		 }
			 if(day != 0){
				 proportion = Math.floor(100/planTotalTime*day);//计算完成比例
			 }else{
				 proportion = Math.floor(100/planTotalTime*1);//计算完成比例
			 }
		}
}
//	if(proportion>100){
//		$("#planPro").val(100);
//	}else{
//		$("#planPro").val(proportion);
//	}
//	var planStartTime = $("#planStartTime").val();
//	var accStartTime = $("#accStartTime").val();
//	if(!checkEndTimeTwo(planStartTime,accStartTime)){
//		$("#planPro").val(100);
//	}
	$("#accDay").val(day);
}

function setImg2(obj) {// 用于进行图片上传，返回地址
	var picList = ".jpg .JPG .png .PNG .jpeg .JEPG";
	var videoList = ".mp4 .MP4 .mov .MOV";
	var f = $(obj).val();
	var jq = f.lastIndexOf("."); 
    var hz = f.substr(jq);
		// 批量上传图片
    if(picList.indexOf(hz) >= 0){
    	if(!/.(jpg|jpeg|png|JPG|PNG|JPEG)$/.test(f)){
    		msgAlert("图片类型必须是jpeg,jpg,png中的一种");
	        return false;
    	}else{
    		 if(((obj.files[0].size).toFixed(2))>=(10*1024*1024)){
    			 msgAlert("请上传小于10M的图片");
    		     return false;
    		 }
    	}
    }else if(videoList.indexOf(hz) >= 0){
    	if(!/.(mp4|MP4|mov|MOV)$/.test(f)){
    		msgAlert("视频类型必须是mp4,mov格式");
	        return false;
    	}else{
    		 if(((obj.files[0].size).toFixed(2))>=(60*1024*1024)){
    			 msgAlert("请上传小于60M的视频");
    		     return false;
    		 }
    	}
    }else{
    	msgAlert("上传的文件格式不正确");
	    return false;
    }
	layer.msg('上传中', {
		icon: 16
		,shade: 0.3,
		offset: 't' //坐标
	});
	var id;
	if(videoList.indexOf(hz) >= 0){
		id = layer.msg('视频转码中', {
			icon: 16
			,shade: 0.3,
			offset: 't', //坐标
			time:false
		});
	}
		$.ajaxFileUpload({
					url : basePath + "/bus/progress/saveProgressAnnex",// 需要链接到服务器地址
					secureuri : false,
					fileElementId : "logoFile2",// 文件选择框的id属性 ,//文件选择框的id属性
					dataType : 'json', // json
					contentType : false, // 不可缺
					processData : false, // 不可缺
					success : function(data) {
						layer.close(id);//手动关闭
						if (data != null) {
							$.each(data.path,function(i, url) {
								var point = url.lastIndexOf("."); 
							    var arr = url.substr(point);
								// 拼接图片/视频列表
								var annex = "annex";
												var id = $(
														'#detailImgs li:last')
														.attr('id');
												id = id.substr(1);
												id = parseInt(id) + 1;
												var ids = id;
												id = 'p' + id;
												var a_hidden = "<li id='"
														+ id
														+ "'><input type='hidden' value='"
														+ url
														+ "' name='imgs'>";
												var img_html="";
												if(picList.indexOf(arr) >= 0 ) {
													img_html = "<img  src='"
														+ url
														+ "'  onclick='showOriginal(this)' original='"
														+ url + "'>";
												}else if(videoList.indexOf(arr) >= 0){
													img_html = "<a href='"+url+"' onclick='showOriginalVideo(this)' target='view_window' width='200px' height='200px'><video width='200px' height='200px' controls><source src='"+url+"' type='video/mp4' /></video></a>"
												}
												var a_html = "<span class = 'hand-like' onclick='delespan2("
														+ ids + ")'>删除</span>";
												var li_html = "</li>";
												$('#detailImgs').append(
														a_hidden + img_html
																+ a_html
																+ li_html);
											});
						} else {
							msgAlert("上传失败");
							$("#url").val("");
							$(obj).val('');
						}
					},
					error : function(XMLHttpRequest, textStatus, errorThrown) {
						msgAlert("上传失败，请检查网络后重试");
						$("#url").val("");
						$(obj).val('');
					}
				});
}
//删除图片
function delespan2(index,id) {
	var id = layer.confirm('确定要删除吗?', {icon: 3, title:'提示',offset:'t'}, function(){
		if(id != null && id != "" && id != "undefined"){
			var url = basePath+"/bus/progress/deleteAnnex?id="+id;
			//showLoad();
				$.ajax({
					type : "post",
					url : url,
					data : id,
					dataType : "json",
					success : function(data) {
						$("#p" + index).remove();
					}
			});
		}else{
			$("#p" + index).remove();
		}
		layer.close(id);//手动关闭
	});
}

function showOriginal(img){
	      var _this = $(img);//将当前的pimg元素作为_this传入函数
	      imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
}


function imgShow(outerdiv, innerdiv, bigimg, _this){
	    var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
	    $(bigimg).attr("src", src);//设置#bigimg元素的src属性
 	        /*获取当前点击图片的真实大小，并显示弹出层及大图*/
 	    $("<img/>").attr("src", src).load(function(){
	        var windowW = $(window).width();//获取当前窗口宽度
 	        var windowH = $(window).height();//获取当前窗口高度
	        var realWidth = this.width;//获取图片真实宽度
 	        var realHeight = this.height;//获取图片真实高度
	        var imgWidth, imgHeight;
 	        var scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放
	         
	        if(realHeight>windowH*scale) {//判断图片高度
 	            imgHeight = windowH*scale;//如大于窗口高度，图片高度进行缩放
 	            imgWidth = imgHeight/realHeight*realWidth;//等比例缩放宽度
	            if(imgWidth>windowW*scale) {//如宽度扔大于窗口宽度
	                imgWidth = windowW*scale;//再对宽度进行缩放
	            }
	        } else if(realWidth>windowW*scale) {//如图片高度合适，判断图片宽度
	            imgWidth = windowW*scale;//如大于窗口宽度，图片宽度进行缩放
	                        imgHeight = imgWidth/realWidth*realHeight;//等比例缩放高度
	        } else {//如果图片真实高度和宽度都符合要求，高宽不变
	            imgWidth = realWidth;
	            imgHeight = realHeight;
	        }
	        $(bigimg).css("width",imgWidth);//以最终的宽度对图片缩放
	        var w = (windowW-imgWidth)/2;//计算图片与窗口左边距
	        var h = (windowH-imgHeight)/2;//计算图片与窗口上边距
	        $(innerdiv).css({"top":h, "left":w});//设置#innerdiv的top和left属性
	        $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
	    });
	     
	    $(outerdiv).click(function(){//再次点击淡出消失弹出层
	        $(this).fadeOut("fast");
	    });
	}

function checkData(){
	//获取表单信息
	var modelPlanId = $("#modelPlanId").val();
	var modelCode = $("#modelCode").val();
	var reportDate = $("#reportDate").val();
	var planProgress= $("#planProgress").val();
	var planPro = $("#planPro").val();
	var targetPre = $("#targetPre").val();
	var currentPro = $("#currentPro").val();
	var accPro = $("#accPro").val();
	var accPre = $("#accPre").val();
	var proStatus = $("#proStatus").val();
	var extDay = $("#extDay").val();
	var extReason = $("#extReason").val();
	/*var useMeter = $("#useMeter").val();
	var useFor = $("#useFor").val();*/
	var remark = $("#remark").val();
	var liList = $("#detailImgs li");
	if (accPro == "" || accPro == null || accPro == "undefined") {
		msgFeedBack("请填写实际完成比例","#accPro");
		return false;
	}
	if (proStatus == "延期") {
		if (extDay == "" || extDay == null || extDay == "undefined") {
			msgFeedBack("请填写延期天数","#extDay");
			return false;
		}
		if (extReason == "" || extReason == null || extReason == "undefined") {
			msgFeedBack("请填写延期原因","#extReason");
			return false;
		}
	}
	/*if (useMeter == "" || useMeter == null || useMeter == "undefined") {
		alert("请填写材料使用数量");
		return false;
	}
	if (useFor == "" || useFor == null || useFor == "undefined") {
		alert("请选择用途");
		return false;
	}*/
	/*if(liList.length == 1){
		msgFeedBack("请上传图片","#uploadPic");
		return false;
	}*/
	return true
} 

function saveProgressDetail(submit_flag){
	if(checkData()){
	//获取表单信息
	var recordId = $("#recordId").val();
	var modelPlanId = $("#modelPlanId").val();
	var modelCode = $("#modelCode").val();
	var reportDate = $("#reportDate").val();
	var planProgress= $("#planProgress").val();
	var planPro = $("#planPro").val();
	var targetPre = $("#targetPre").val();
	var currentPro = $("#currentPro").val();
	var accPro = $("#accPro").val();
	var accPre = $("#accPre").val();
	var proStatus = $("#proStatus").val();
	var extDay = $("#extDay").val();
	var extReason = $("#extReason").val();
	var modelProcessId = $("#modelProcessId").val();
	/*var useMeter = $("#useMeter").val();
	var useFor = $("#useFor").val();*/
	var remark = $("#remark").val();
	if (extDay == "" || extDay == null || extDay == "undefined") {
		extDay = 0;
	}
	if (accPre == "" || accPre == null || accPre == "undefined") {
		accPre = 0;
	}
	var pcoResult = [];
	var data = {
			id : recordId,
			modelPlanId : modelPlanId,
			modelCode : modelCode,
			reportDate : reportDate,
			planProgress : planProgress,
			planPro : planPro,
			targetPre : targetPre,
			currentPro : currentPro,
			accPro : accPro,
			accPre : accPre,
			proStatus : proStatus,
			extDay : extDay,
			extReason : extReason,
			modelProcessId : modelProcessId,
			/*useMeter : useMeter,
			useFor : useFor,*/
			submitFlag : submit_flag,
			remark : remark
		};
	pcoResult.push(data);
	
	var liList = $("#detailImgs li");//获取图片地址
	var picResult = [];
	for (var i=1;i<liList.length;i++) {
		var liArr = liList.eq(i).find("img");
		var url="";
		var type=""
		if(liArr.length>0){
			url = liArr.eq(0).attr("src");//
			type="PIC";
		}else{
			var liArr = liList.eq(i).find("video");
			url = liArr.find("source").eq(0).attr("src");//
			type = "VIDEO"
		}
		var id = liArr.eq(0).attr("id");//
		picResult.push({'id':id,'type':type,'path':url});
	}
	var url = basePath+"/bus/progress/editProgressDetail";
	showLoad();
		$.ajax({
			type : "post",
			url : url,
			data : {pcoData:JSON.stringify(pcoResult),picData:JSON.stringify(picResult)},
			dataType : "json",
			success : function(data) {
				msgPrompt(data.message);
				// toIndex();
                window.location.href=basePath +'/bus/meter/returnMeterGive?url='+basePath+'/bus/progress/myProgressReport&flg=myProgressReport';
			}
		});
	}
}
//页面跳转
function toIndex(){
	var mapType = $("#mapType").val();
	var mapStatus = $("#mapStatus").val();
	var mapCode = $("#mapCode").val();
	var mapPage = $("#mapPage").val();
	var url = basePath+"/bus/progress/myProgressReport?modelCode="+mapCode+"&modelType="+mapType+"&status="+mapStatus+"&page="+mapPage;
	window.location.href=url;
}

function uploadAnnex(){
	$("#logoFile2").click(); 
}
